package com.tiancheng.onecode.model.response;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tiancheng.onecode.utils.JsonUtil;

import java.util.Map;

/**
 * 返回实体
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result<T> {
	private T data;
	private Integer errorCode;
	private String msg;
	private Integer ret;
	private String traceId;

	public Result(T data) {
		this.data = data;
		this.errorCode = 0;
		this.msg = "success";
		this.ret = 0;
	}

	public Result() {
		this(null);
	}

	public static <Ts> Result<Ts> success(Ts data) {
		return new Result(data);
	}

	public static Result<Void> success() {
		return new Result((Object)null);
	}

	public static <Ts> Result<Ts> fail(int errorcode, String msg, Ts data) {
		if (errorcode == 0) {
			throw new IllegalArgumentException("errorcode can't be 0");
		} else {
			Result<Ts> result = new Result();
			result.setErrorCode(errorcode);
			result.setMsg(msg);
			result.setRet(1);
			result.setData(data);
			return result;
		}
	}

	public static Result<Void> fail(int errorcode, String msg) {
		return fail(errorcode, msg, null);
	}

	public static Result<Void> fail(String msg) {
		return fail(500, msg);
	}

	public static <Ts> Result<Ts> fail(String msg, Ts data) {
		return fail(500, msg, data);
	}

	public boolean resultIsError() {
		if (this.errorCode != null && this.ret != null) {
			return this.errorCode != 0 || this.ret != 0;
		} else {
			return true;
		}
	}

	public String toString() {
		return JsonUtil.toJsonString(this.data);
	}

	public T getData() {
		return this.data;
	}

	public Integer getErrorCode() {
		return this.errorCode;
	}

	public String getMsg() {
		return this.msg;
	}

	public Integer getRet() {
		return this.ret;
	}

	public String getTraceId() {
		return this.traceId;
	}

	public Result<T> setData(T data) {
		this.data = data;
		return this;
	}

	public Result<T> setErrorCode(Integer errorCode) {
		this.errorCode = errorCode;
		return this;
	}

	public Result<T> setMsg(String msg) {
		this.msg = msg;
		return this;
	}

	public Result<T> setRet(Integer ret) {
		this.ret = ret;
		return this;
	}

	public Result<T> setTraceId(String traceId) {
		this.traceId = traceId;
		return this;
	}
}
